#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <list>

typedef struct _OneTrace
{
   char * start;
   char * end;
   int quantity;
}OneTrace;

#define MAX_QUANTITY 480

int split_trace(char * traceIn, int lenIn, 
                int quantity_air, int quantity_spit, int quantity_suck,
                std::list<OneTrace>& tracesOut)
{
    int suckAll = quantity_air + quantity_suck;
    int maxSpit = MAX_QUANTITY - quantity_spit;

    char * ptrBuff = traceIn;
    
    char * ptrTemp = ptrBuff;
    
    char buffOneHole[64];
    memset(buffOneHole,0,64);
    
    ptrBuff = strchr(ptrBuff,',');

    OneTrace oneTrace;
    oneTrace.start = traceIn;
    oneTrace.quantity = 0;
    oneTrace.end = traceIn;
    
    int quantity1Hole = 0;
  
    while(ptrBuff)
    {
         memcpy(buffOneHole,ptrTemp,ptrBuff-ptrTemp); 
         quantity1Hole = atoi(ptrTemp+2);
         oneTrace.quantity += quantity1Hole;
         if(oneTrace.quantity > maxSpit)
         {
            oneTrace.end = ptrTemp - 1;
            oneTrace.quantity -= quantity1Hole;
            tracesOut.push_back(oneTrace);
            
            oneTrace.start = ptrTemp;
            oneTrace.quantity = quantity1Hole;
         }
         ptrTemp = ptrBuff+1;
         ptrBuff = strchr(ptrTemp,',');
         memset(buffOneHole,0,64);
    }


    if(strlen(ptrTemp))
    {
        quantity1Hole = atoi(ptrTemp+2);
        oneTrace.quantity += quantity1Hole;
        if(oneTrace.quantity > maxSpit)
        {
            oneTrace.end = ptrTemp - 1;
            oneTrace.quantity -= quantity1Hole;
            tracesOut.push_back(oneTrace);
            
            oneTrace.start = ptrTemp;
            oneTrace.quantity = quantity1Hole;
        }
    }

    oneTrace.end = ptrTemp + strlen(ptrTemp);
    tracesOut.push_back(oneTrace);
    return 0;
}

int main(int argc,char * argv[])
{
    char strTraceAll[1024] = "Aa50,Ab50,Ac50,Ad50,Ae50,Af50,Ag50,Ah50,\
Bh50,Bg50,Bf50,Be50,Bd50,Bc50,Bb50,Ba50,\
Ca50,Cb50,Cc50,Cd50,Ce50,Cf50,Cg50,Ch50";
    std::list<OneTrace> tracesResult;
    int quantitySuckAll = 1300;
    split_trace(strTraceAll,strlen(strTraceAll),5,5,1200,tracesResult);

    std::list<OneTrace>::iterator itTrace = tracesResult.begin();
    
    int traceNum = tracesResult.size();

    char buffOneTrace[256];
    

    for(int i=0;i<traceNum;i++)
    {
       memset(buffOneTrace,0,256);
       memcpy(buffOneTrace,itTrace->start,itTrace->end - itTrace->start);
       quantitySuckAll -= itTrace->quantity;
       
       if(quantitySuckAll<0)
       {
            printf("quantity suck is not enough\n");
            break;
       }
       
       if(i==(traceNum-1))
       {
           if(0 < quantitySuckAll)
           {
                itTrace->quantity = quantitySuckAll + itTrace->quantity;
           }
       }
       printf("trace:%s ;quantity:%d\n",buffOneTrace,itTrace->quantity);
       itTrace++;
       
    }

    tracesResult.clear();
    
}



